package com.nine.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nine.entity.Account;
import com.nine.entity.ConfirmPaycode;
import com.nine.entity.Order;
import com.nine.entity.Orderitems;
import com.nine.entity.Package;
import com.nine.entity.Product;
import com.nine.entity.Users;
import com.nine.entity.Vips;
import com.nine.service.OrderService;


@Controller
@RequestMapping("/")
public class OrderController {
	@Autowired
	private OrderService orderService;
	@org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(HttpServletRequest request,
            ServletRequestDataBinder binder) {
        // 不要删除下行注释!!! 将来"yyyy-MM-dd"将配置到properties文件中
        // SimpleDateFormat dateFormat = new
        // SimpleDateFormat(getText("date.format", request.getLocale()));
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd");  // HH:mm:ss
        dateFormat.setLenient(false);
        binder.registerCustomEditor(java.util.Date.class, null, new CustomDateEditor(
                dateFormat, true));
    }
	@RequestMapping(value="showvip.do")
	public String getAllVips(HttpSession session,Model model)throws Exception{
		String nomvip=(String) session.getAttribute("nomvip");
		String username=(String) session.getAttribute("username");
		Users user=orderService.getOneUser(username);
		int accountid=Integer.parseInt(orderService.getOneUser(nomvip).getAccountid());
		Account acc=orderService.getOneAccount(accountid);
		List<Vips> list=orderService.getAllVips();
		model.addAttribute("acc", acc);
		model.addAttribute("user", user);
		model.addAttribute("list", list);
		return "m_shop/viporder.jsp";
	}
	@RequestMapping(value="savename.do")
	public String saveName(HttpServletRequest request,HttpSession session,Model model)throws Exception{
		String username=request.getParameter("username");
		session.setAttribute("username", username);
		session.setAttribute("nomvip", "tz");
		return "showvip.do";
	}
	@ResponseBody
	@RequestMapping(value="checkuser.do")
	public Integer checkUser(String username)throws Exception{
		Integer temp=-1;
		Users user=orderService.getOneUser(username);
		if(user!=null) {
			if(user.getViptype().equals("注册会员")) {
				temp=1;
			}
			else {
				temp=0;
			}
		}
		return temp;
	}
	@RequestMapping(value="confirmpw.do")
	public String confirmpw(Model model,HttpServletRequest request,HttpServletResponse response,HttpSession session)throws Exception{
		//获取弹窗中输入的二级密码
		//System.out.println("yizongtao");
		int paycode=Integer.parseInt(request.getParameter("paycode"));
		System.out.println("123"+paycode);
		//获取登录用户名
		String nomvip=(String) session.getAttribute("nomvip");
		System.out.println("234"+nomvip);
		//获取单选框中的VIP类型
		String viptype=request.getParameter("viptype");
		System.out.println("vip类型"+viptype);
		//获取单选框中vip对应的价格
		int money=orderService.getOneVip(viptype).getMoney();
		System.out.println("VIP对应价格"+money);
		//获取用户的真实姓名
		String holder=orderService.getOneUser(nomvip).getRealname();
		System.out.println("真实姓名"+holder);
		//将二级密码和真实姓名存入验证密码实体（ConfirmPaycode）
		ConfirmPaycode confirmPaycode=new ConfirmPaycode();
		confirmPaycode.setHolder(holder);
		confirmPaycode.setPaycode(paycode);
		//通过真实姓名和二级密码匹配对应的银行账户
		Account account=orderService.getOneAccount(confirmPaycode);
		//System.out.println("账户余额"+account.getMoney());
		if(account!=null) {
			//判断账户余额是否大于对应VIP价格money=vip价格，account=个人账户
			if(money<=account.getMoney()) {
				//获取需要购买会员的会员名
				String username=(String) session.getAttribute("username");
				//获取随机四位数，生成会员单号
				int fournumber= (int)((Math.random()*9+1)*1000);
				String viporder="sl_gh"+fournumber;
				//将会员类型，用户名，会员单号存入users实体当中
				Users user=new Users();
				user.setViptype(viptype);
				user.setViporder(viporder);
				user.setUsername(username);
				int temp=orderService.changeVipOrder(user);
				System.out.println("改变viporder"+temp);
				System.out.println("用户的viporder"+user.getViporder());
				return "m_shop/confirm.jsp";
			}else {
				return "m_shop/notenough.jsp";
		}
		}else {
			return "m_shop/errorpaycode.jsp";
		}
		}
	//套餐购物相关
	@ResponseBody
	@RequestMapping(value="comboShop.do")
	public Map<String ,Object> comboShop(Integer limit, Integer page,String pgid,String pgname)throws Exception{
		Package package1=new Package();
		package1.setPgid(pgid);
		package1.setPgname(pgname);
		//1.启用分页
		PageHelper.startPage(page, limit); //传页码，页大小
		//2.查询
		//执行查询修改sql，自动添加limit进行分页
		List<Package> list=orderService.getAllPackage(package1);
				
		//3.获取分页后的相关信息
		PageInfo<Package> pageInfo=new PageInfo<Package>(list);
		Integer count = (int) pageInfo.getTotal();
		//layui对返回数据的json格式要求
		Map<String,Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", 0);
		resultMap.put("msg", "");
		resultMap.put("count", count);
		resultMap.put("data", list);
		return resultMap;
	}
	//获取单条购物相关
	@ResponseBody
	@RequestMapping(value="singleShop.do")
	public Map<String ,Object> singleShop(Integer limit, Integer page,String pid,String pname)throws Exception{
		//System.out.println("编号"+pid+"民称"+pname);
		//Package package1=new Package();
		//package1.setPgid(pgid);
		//package1.setPgname(pgname);
		Product product=new Product();
		
		product.setPid(pid);
		product.setPname(pname);
		//1.启用分页
		PageHelper.startPage(page, limit); //传页码，页大小
		
		//2.查询
		//执行查询修改sql，自动添加limit进行分页
		//List<Package> list=orderService.getAllPackage(package1);
			List<Product> list=orderService.getSomethingProduct(product);
		
		//3.获取分页后的相关信息
		PageInfo<Product> pageInfo=new PageInfo<Product>(list);
		Integer count = (int) pageInfo.getTotal();
		//layui对返回数据的json格式要求
		Map<String,Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", 0);
		resultMap.put("msg", "");
		resultMap.put("count", count);
		resultMap.put("data", list);
		/*for (Product p : list) {
			System.out.println(p.getPname());
		}*/
		return resultMap;
	}
	//添加单品购物车
	@ResponseBody
	@RequestMapping(value="addSingleShopping.do")
	public Integer addShopping(HttpSession session,HttpServletRequest request,@RequestBody Product product)throws Exception{
		    System.out.println("实体"+product);  
		   System.out.println("数据"+product.getPid());   
		   Order order=new Order();
			Integer temp=-1;
			int fournumber;
			System.out.println("这是准备得到所有的订单");
			List<Order> list=orderService.getAllOrders();
			System.out.println("这是得到所有订单");
			for (Order o : list) {
				if(o.getState()==0)temp=1; 
			}
			if(temp==1) {
				fournumber=(int) session.getAttribute("fournumber");
			}else {
				fournumber= (int)((Math.random()*9+1)*1000);
				session.setAttribute("fournumber", fournumber);
			}
			System.out.println("自动生成的订单号"+fournumber);
			String oid="sl_or"+fournumber;
		    Orderitems orderitems=new Orderitems();
		    orderitems.setOid(oid);
		    orderitems.setPid(product.getPid());
		    int res=orderService.addSingleShopping(orderitems);


		return res;
	}
	
	
	
	//添加套餐购物车
	@ResponseBody
	@RequestMapping(value="addComboShopping.do")
	public Integer addShopping(HttpSession session,HttpServletRequest request,@RequestBody Package package1)throws Exception{
		 System.out.println("实体"+package1);  
		   System.out.println("数据"+package1.getPgid());  
		Order order=new Order();
		Integer temp=-1;
		int fournumber;
		System.out.println("这是准备得到所有的订单");
		List<Order> list=orderService.getAllOrders();
		System.out.println("这是得到所有订单");
		for (Order o : list) {
			if(o.getState()==0)temp=1; 
		}
		if(temp==1) {
			fournumber=(int) session.getAttribute("fournumber");
		}else {
			fournumber= (int)((Math.random()*9+1)*1000);
			session.setAttribute("fournumber", fournumber);
		}
		System.out.println("自动生成的订单号"+fournumber);
		String oid="sl_or"+fournumber;
		order.setOid(oid);
		String nomvip=(String) session.getAttribute("nomvip");
		Users user=orderService.getOneUser("kx");
		order.setUid(user.getId());
		order.setType("套餐购物");
		order.setPackageid("2");
		order.setState(0);
		System.out.println("我是来的到套餐价格的"+package1.getPrice());
		order.setMoney(package1.getPrice());
		int res=orderService.addShopping(order);
		return res;
	}
	
	
	
	//购物车
/*	@ResponseBody
	@RequestMapping(value="showOrder.do")
	public List<Order> showOrder(HttpSession session)throws Exception{
		//获取登录用户名
		String nomvip=(String) session.getAttribute("nomvip");
		Order order=new Order();
		List<Order> list1=null;
		List<Order> list=orderService.getAllOrders();
		for (Order o : list) {
			if(o.getState()==0)list1.add(o);
		}
		
		
		
		return list1;
	}*/
	@ResponseBody
	@RequestMapping(value="showOrder.do")
	public Map<String ,Object> comboShop(Integer limit, Integer page,HttpSession session)throws Exception{
		//String nomvip=(String) session.getAttribute("nomvip");
		
		List<Order> list1=null;
		List<Order> list=orderService.getAllOrders();
		System.out.println("我在测试查所有"+list);
		list1= new ArrayList<Order>();
		for (Order o : list) {
			
			if(o.getState()==0) {
				
				list1.add(o); 
				}
			
		}
		//1.启用分页
		PageHelper.startPage(page, limit); //传页码，页大小
		//2.查询
		//执行查询修改sql，自动添加limit进行分页
		//List<Package> list=orderService.getAllPackage(package1);
				
		//3.获取分页后的相关信息
		PageInfo<Order> pageInfo=new PageInfo<Order>(list1);
		Integer count = (int) pageInfo.getTotal();
		//layui对返回数据的json格式要求
		Map<String,Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", 0);
		resultMap.put("msg", "");
		resultMap.put("count", count);
		resultMap.put("data", list1);
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value="delshopping.do")
	public int delshopping(Integer id)throws Exception{
		int temp=orderService.delShopping(id);
		return temp;
		
	}
	@ResponseBody
	@RequestMapping(value="buy.do")
	public int buy()throws Exception{
		int i=0;
		int res=0;
		List<Order> list=orderService.getAllOrders();
		for (Order o : list) {
			if(o.getState()==0) {
				Order order=new Order();
				order.setId(o.getId());
				order.setState(1);
				orderService.updateOrderState(order);
			i++;
			}
		}
		if(i!=0) {
			res=1;
		}
		return res;
	}
	@ResponseBody
	@RequestMapping(value="orderBuy.do")
	public Map<String ,Object> orderBuy(Integer limit, Integer page,HttpSession session)throws Exception{
		//String nomvip=(String) session.getAttribute("nomvip");
		
		List<Order> list1=null;
		List<Order> list=orderService.getAllOrders();
		System.out.println("我在测试查所有"+list);
		list1= new ArrayList<Order>();
		for (Order o : list) {
			
			if(o.getState()==0) {
				
				list1.add(o); 
				}
			
		}
		//1.启用分页
		PageHelper.startPage(page, limit); //传页码，页大小
		//2.查询
		//执行查询修改sql，自动添加limit进行分页
		//List<Package> list=orderService.getAllPackage(package1);
				
		//3.获取分页后的相关信息
		PageInfo<Order> pageInfo=new PageInfo<Order>(list1);
		Integer count = (int) pageInfo.getTotal();
		//layui对返回数据的json格式要求
		Map<String,Object> resultMap = new HashMap<String, Object>();
		resultMap.put("code", 0);
		resultMap.put("msg", "");
		resultMap.put("count", count);
		resultMap.put("data", list);
		return resultMap;
	} 
}
